package cn.rocksolid.proxy.restful.agency;

import cn.rocksolid.sport.agency.entity.SmtpSettingEntity;
import cn.rocksolid.sport.agency.service.SmtpSettingService;
import cn.rocksolid.sport.common.error.RSE;
import cn.rocksolid.sport.common.http.R;
import cn.rocksolid.sport.common.http.utils.HttpUtils;
import cn.rocksolid.sport.common.utils.AssertUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("agency/smtp-setting")
public class SmtpSettingController {

  private final SmtpSettingService smtpSettingService;

  @Autowired
  public SmtpSettingController(final SmtpSettingService smtpSettingService) {
    this.smtpSettingService = smtpSettingService;
  }

  /**
   * Pagination of agency SMTP settings
   */
  @PostMapping("/page")
  @RequiresPermissions("agency:smtp-setting:info")
  public Object page(@RequestBody final JSONObject cond) {
    return smtpSettingService.paging(HttpUtils.resolve(), cond);
  }

  /**
   * Get
   */
  @GetMapping("/{id}")
  @RequiresPermissions("agency:smtp-setting:info")
  public Object get(@PathVariable("id") final String id) {
    return smtpSettingService.getById(id);
  }

  /**
   * create
   */
  @PutMapping
  @RequiresPermissions("agency:smtp-setting:create")
  public Object create(@RequestBody final SmtpSettingEntity smtpSettingEntity) {
    smtpSettingValidator(smtpSettingEntity);
    smtpSettingService.save(smtpSettingEntity);
    return R.ok();
  }

  /**
   * modify
   */
  @PostMapping
  @RequiresPermissions("agency:smtp-setting:modify")
  public Object modify(@RequestBody final SmtpSettingEntity smtpSettingEntity) {
    smtpSettingValidator(smtpSettingEntity);
    smtpSettingService.updateById(smtpSettingEntity);
    return R.ok();
  }

  /**
   * remove
   */
  @DeleteMapping
  @RequiresPermissions("agency:smtp-setting:remove")
  public Object remove(@RequestBody final List<String> ids) {
    smtpSettingService.removeByIds(ids);
    return R.ok();
  }

  /**
   * validate agency smtpSetting
   */
  public void smtpSettingValidator(SmtpSettingEntity smtpSettingEntity) {
    AssertUtils.isNotNull(smtpSettingEntity, RSE.INVALID_PAYLOAD);
    AssertUtils.isNotNull(smtpSettingEntity.getHost(), RSE.INVALID_AGSMTPS_HOST);
    AssertUtils.isNotNull(smtpSettingEntity.getPort(), RSE.INVALID_AGSMTPS_PORT);
    AssertUtils.isEmail(smtpSettingEntity.getEmail(), RSE.INVALID_EMAIL);
  }
}
